import axios, { type Method } from 'axios'
import { useUserStore } from '@/stores'
import { showToast } from 'vant'
import router from '@/router'
const baseURL = 'https://consult-api.itheima.net/'
const instance = axios.create({
  // TODO 1. 基础地址，超时时间
  baseURL,
  timeout: 10000
})

instance.interceptors.request.use(
  (config) => {
    // TODO 2. 携带token
    const stores = useUserStore()
    if (stores.user?.token) {
      config.headers['Authorization'] = `Bearer ${stores.user?.token}`
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    if (res.data?.code !== 10000) {
      // TODO 3. 处理业务失败
      showToast(res.data?.message || '业务失败')
      return Promise.reject(res.data)
    }
    // TODO 4. 摘取核心响应数据
    // console.log(res.data);

    return res.data
  },
  (err) => {
    if (err.response.status === 401) {
      const stores = useUserStore()
      stores.delUser()
      router.push({
        // 跳转登录，带上接口失效所在页面的地址，登录完成后回跳使用
        path: '/login',
        query: { returnUser: router.currentRoute.value.fullPath }
      })
    }
    // TODO 5. 处理401错误
    return Promise.reject(err)
  }
)

export { instance, baseURL }

type Data<T> = {
  code: number
  massage: string
  data: T
}
export const request = <T>(
  url: string,
  method: Method = 'get',
  submitData?: object
) => {
  return instance.request<T, Data<T>>({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
  })
}
